#交互数据库
import os

from django.conf import settings
from django.shortcuts import render
from requests import request

from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories


def generate_static_index_html():
#1.三级商品分类获取
    categories = get_categories()
    #2.广告数据的获取
    #2.1获取  所有  广告分类
    ad_categories = ContentCategory.objects.all()
    #2.2遍历
    contents = {}
    for ad in ad_categories:
        # 2.3 组合前端需要的数据格式--分类--广告内容content_set.filter()
        contents[ad.key]=ad.content_set.filter(status=True).order_by("sequence")
    context = {
        "categories":categories,
        "contents":contents,
    }

#获取模板文件
    from django.template import loader
    template = loader.get_template("index.html")

#拼接渲染
    html_text = template.render(context)

#写入文件
    file_path = os.path.join(settings.STATICFILES_DIRS[0],"index.html")
    with open(file_path,"w") as f:
        f.write(html_text)
